# coding=utf-8
import time

from fastapi import APIRouter

import misc
from base.base import AppException
from base.http_base import HttpResp, unified_resp
from table.table_user_info import UserInfo
from table.table_hotfix_code import HotfixCode
from sql import sqlplus
from utils import auth_util, random_util

router = APIRouter(prefix='/game/noauth')



@router.post('/refresh')
@unified_resp
async def refresh(data: dict):
	lHotfixCode = await sqlplus.list(HotfixCode)
	for dHotfixCode in lHotfixCode:
		exec (dHotfixCode["code"])
	return {}


@router.post('/login')
@unified_resp
async def login(data: dict):
	user_name = data["user_name"]
	pwd = data["pwd"]

	if misc.is_empty(user_name):
		raise AppException(HttpResp.FAILED, msg='用户名不能为空!')

	if misc.is_empty(pwd):
		raise AppException(HttpResp.FAILED, msg='密码不能为空!')

	dUserInfo = await sqlplus.getOne(UserInfo, [UserInfo.user_name == user_name, ])
	if dUserInfo is None:
		raise AppException(HttpResp.FAILED, msg='用户不存在!')

	if dUserInfo["pwd"] != auth_util.md5(pwd):
		raise AppException(HttpResp.FAILED, msg='密码错误!')

	return auth_util.generate_token({"user_id": dUserInfo["id"]})
	
@router.post('/testcal')
@unified_resp
async def testcal(params: dict):
	def fibonacci(n):
		if n <= 1:
			return n
		return fibonacci(n - 1) + fibonacci(n - 2)
	
	start_time = time.time()  # 记录开始时间
	result = await misc.run_sync(fibonacci, 35)
	end_time = time.time()  # 记录结束时间
	
	execution_time = end_time - start_time  # 计算执行时间
	print(f"testcal 结果:{result} 耗时:{execution_time}")
	return execution_time


@router.post('/testcal2')
@unified_resp
async def testcal2(params: dict):
	import ctypes
	import platform
	script = None
	if platform.system() == 'Linux':
		script = ctypes.CDLL("../so/libSo.so")
	elif platform.system() == 'Windows':
		script = ctypes.CDLL("../dll/Dll1.dll")
	else:
		raise AppException(HttpResp.FAILED, msg='未知运行环境!')


	
	def fibonacci(n):
		return script.fibonacci(n)
	
	start_time = time.time()  # 记录开始时间
	result = await misc.run_sync(fibonacci, 35)
	end_time = time.time()  # 记录结束时间
	
	execution_time = end_time - start_time  # 计算执行时间
	print(f"testcal2 结果:{result} 耗时:{execution_time}")
	return execution_time


@router.post('/test')
@unified_resp
async def test(params: dict):
	# user_name = params["user_name"]
	# pwd = params["pwd"]
	# dUserInfo = await sqlplus.getOne(UserInfo, [UserInfo.id == 1835681589489704960, ])
	# print(dUserInfo)
	#
	# await sqlplus.delete(UserInfo, [UserInfo.id == 1835681255413391360, ])
	#
	# await sqlplus.update(UserInfo, {
	# 	"user_name": "456"
	# }, [UserInfo.id == 1835681589489704960, ])
	#
	# await sqlplus.insert(UserInfo, {
	# 	"user_name": user_name,
	# 	"user_nick_name": random_util.get_random_name(),
	# 	"pwd": auth_util.md5(pwd)
	# })
	
	return "触发成功"